package socket.homework3;

import socket.example4.StreamUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author lhn
 * @date 2024-04-27 20:17
 */

public class Homework03Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端启动成功，端口9999等待请求...");
        Socket socket = serverSocket.accept();

        //从通道中取出客户端要请求的文件名
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream)
        );
        String filename = bufferedReader.readLine();
        System.out.println("客户端请求的文件为:" + filename);

        boolean isExist = FileExistenceCheck("F:\\music\\",filename);
        //通过发送一条isExist让客户端知道是否需要接收文件
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(
                new OutputStreamWriter(outputStream)
        );
        bufferedWriter.write(String.valueOf(isExist));
        bufferedWriter.newLine();
        bufferedWriter.flush();

        if (isExist) {
            System.out.println("文件存在");
            //创建一个输入流，将磁盘上的文件读入缓存
            BufferedInputStream bufferedInputStream = new BufferedInputStream(
                    new FileInputStream("F:\\music\\" + filename)
            );
            //使用工具类StreamUtils
            byte[] bytes = StreamUtils.streamToByteArray(bufferedInputStream);
            outputStream = socket.getOutputStream();
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
                    outputStream
            );
            //把文件写入数据通道
            bufferedOutputStream.write(bytes);
            socket.shutdownOutput();

            bufferedInputStream.close();
            bufferedOutputStream.close();
            System.out.println("已向客户端发送请求的文件");
        } else {
            System.out.println("文件不存在");
        }
        inputStream.close();
        socket.close();
        serverSocket.close();
        System.out.println("服务端关闭...");
    }

    public static boolean FileExistenceCheck(String directory , String filename) {
        Path path = Paths.get(directory, filename);
        boolean isExist = Files.exists(path);
        if (isExist) {
            return true;
        }
        return false;
    }
}
